<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// | 该文件的开源协议以所在项目的LICENSE文件为准，请遵守开源协议要求
// +----------------------------------------------------------------------
// | 配置
// +----------------------------------------------------------------------
namespace app\cms\http\api;

use app\admin\attributes\auth;
use Inphp\Core\Modules;
use Inphp\Core\Object\Message;
use Inphp\Core\Util\Str;

class config
{
    public function index(): Message
    {
        return httpMessage(Modules::getModule("cms")->getConfig());
    }

    #[auth("cms/config")] public function save(): Message
    {
        $config = POST("config") ?? getClient()->post;
        //
        $cache = $config["cache"] ?? false;
        $cacheTime = $config["cacheTime"] ?? 86400;
        $cacheTime = is_numeric($cacheTime) && $cacheTime >= 3600 ? $cacheTime : 86400;
        $cacheTime = min($cacheTime, 7 * 86400);
        $illegalString = $config["illegalString"] ?? "";
        $illegalString = !empty($illegalString) ? Str::trim($illegalString) : "";
        if (!empty($illegalString)) {
            $illegalString = str_replace("、", ",", $illegalString);
            $illegalString = str_replace("|", ",", $illegalString);
            $illegalString = str_replace("，", ",", $illegalString);
            $list = explode(",", $illegalString);
            $array = [];
            foreach ($list as $val) {
                $val = !empty($val) ? Str::trim($val) : "";
                if (!empty($val) && !in_array($val, $array)) {
                    $array[] = $val;
                }
            }
            $illegalString = join(",", $array);
        }
        $config = [
            "cache"     => $cache !== false,
            "cacheTime" => $cacheTime,
            "illegalString" => $illegalString
        ];
        if(!\Inphp\Core\Modules::getModule("cms")->saveConfig("config", $config)) {
            return httpMessage("配置文件保存失败，请检测是否有写入权限！");
        }
        return httpMessage(0, "配置保存成功");
    }
}